package com.recipe.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.recipe.common.config.RedisUtil;
import com.recipe.entity.User;
import com.recipe.entity.vo.DishVo;
import com.recipe.enums.DishLikedStatusEnum;
import com.recipe.mapper.DishLikedMapper;
import com.recipe.entity.DishLiked;
import com.recipe.service.DishLikedService;
import com.recipe.service.UserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * (DishLiked)表服务实现类
 *
 * @author lzk
 * @since 2024-06-18 09:24:27
 */
@Service("dishLikedService")
@RequiredArgsConstructor
public class DishLikedServiceImpl extends ServiceImpl<DishLikedMapper, DishLiked> implements DishLikedService {


    private final RedisUtil redisUtil;

    private final UserService userService;

    private static final String DISH_LIKED_KEY = "dish.liked";

    private static final String DISH_LIKED_COUNT_KEY = "dish.liked.count";

    private static final String DISH_LIKED_DETAIL_KEY = "dish.liked.detail";

    @Override
    public void add(DishLiked dishLiked) {

        Long userId = dishLiked.getUserid();
        Long dishId = dishLiked.getDishid();
        String hashKey = buildKey(userId.toString(),dishId.toString());
        int status=1;
        if(isLiked(dishId.toString(),userId.toString())){
            status = 0;
        }
        redisUtil.putHash(DISH_LIKED_KEY,hashKey,status);
        String detailKey = DISH_LIKED_DETAIL_KEY + "." + dishId + "." + userId;
        String countKey = DISH_LIKED_COUNT_KEY + "." + dishId;
        if(DishLikedStatusEnum.LIKED.code==status){
            redisUtil.increment(countKey, 1);
            redisUtil.set(detailKey, "1");
        }else{
            Integer count = redisUtil.getInt(countKey);
            if (Objects.isNull(count) || count <= 0) {
                return;
            }
            redisUtil.increment(countKey, -1);
            redisUtil.del(detailKey);
        }
    }

    @Override
    public Integer getLikedCount(long dishId) {
        String countKey = DISH_LIKED_COUNT_KEY + "." + dishId;
        Integer count = redisUtil.getInt(countKey);
        if (Objects.isNull(count) || count <= 0) {
            return 0;
        }
        return count;
    }

    @Override
    public void synLiked() {
        Map<Object, Object> dishLikedHash = redisUtil.getHashAndDelete(DISH_LIKED_KEY);
        if (MapUtils.isEmpty(dishLikedHash)) {
            return;
        }
        List<DishLiked> dishLikedList=new ArrayList<>();
       dishLikedHash.forEach((key,value)->{
           DishLiked dishLiked=new DishLiked();
           String[] split = key.toString().split(":");
           String dishId=split[0];
           String userId1=split[1];

           dishLiked.setDishid(Long.valueOf(dishId));
           dishLiked.setUserid(Long.valueOf(userId1));

           dishLiked.setStatus(Integer.valueOf(value.toString()));

           dishLikedList.add(dishLiked);
       });

       this.saveOrUpdateBatch(dishLikedList);

    }

    @Override
    public void deleteById(DishVo dishVo) {
        long dishId = dishVo.getDishId();
        this.removeById(dishId);
        User currentUser = userService.getUserByUserName(dishVo.getUsername());
        Long userId = currentUser.getId();
        redisUtil.del(DISH_LIKED_DETAIL_KEY + "." + dishId+"."+userId);
        redisUtil.increment(DISH_LIKED_COUNT_KEY + "." + dishId, -1);
        try {
            Thread.sleep(1000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        redisUtil.del(DISH_LIKED_DETAIL_KEY + "." + dishId+"."+userId);

    }

    public Boolean isLiked(String dishId, String userId) {
        String detailKey = DISH_LIKED_DETAIL_KEY + "." + dishId + "." + userId;
        return redisUtil.exist(detailKey);
    }
    public String buildKey(String userId,String dishId){
        return dishId + ":" + userId;
    }




}

